<!-- 上传案例添加页面 -->
<script src="https://cdn.bootcss.com/plupload/2.1.8/plupload.full.min.js"></script>
<script type="text/javascript" charset="utf-8" src="/uedit/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.staticfile.org/ueditor/1.4.3/ueditor.all.js"> </script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="/uedit/lang/zh-cn/zh-cn.js"></script>
<link rel="stylesheet" href="/css/topicApps_add.css">
<style type="text/css">
	.price-num {
		display: inline-block;
		width: 140px;
		height: 30px;
	}
	.button-add {
	    display: block;
	    text-align: center;
	    width: 20%;
	    height: 40px;
	    line-height: 40px;
	    color: #fff;
	    background: linear-gradient(90deg, #29D5F6, #6840E0 );
	    border-radius: 2px;
	    border: 0;
	    box-shadow: 0 2px 17px 0 rgba(0,87,255,0.51);
	    cursor: pointer;
	}
	.main {
	   padding-bottom: 60px;
	}
	.price-none{
		display:none;
	}
	.layui-btn-primary{
		background:#fff;
		border-color: #494f7f;
	}
	.layui-btn-primary:focus{
	    border-color: #C9C9C9!important;
	}
	.layui-btn-primary:hover{
	    border-color: #D2D2D2!important;
	}
</style>

<div class="main layui-clear">
	<div class="wrap layui-clear">
		<div class="layui-bar">
			<div class="layui-breadcrumbs">
				<a class="home" href="/"></a>
				<i class="layui-icon">&#xe602;</i>
		  		<a href="/microcase/downlist.html">micro：bit案例上传</a>
			</div>
		</div>
		<div class="layui-form layui-form-pane">
			<form id="myForm" action="" method="post" onkeydown="if(event.keyCode==13){return false;}">
			
				<input type="hidden" name="id" id="id" value="${microcaseData.id!''}">
				<input type="hidden" name="creater" id="creater" value="${microcaseData.creater!''}">
				<input type="hidden" name="official" id="official" value="${microcaseData.official!''}">
				<input type="hidden" name="parts" id="parts" placeholder="配件"  value="">
				<input type="hidden" name="releasetime" id="releasetime" placeholder="发布时间"   value="${microcaseData.releasetime!''}">
				
				<input type="hidden" name="filelogo" id="filelogo" value="${microcaseData.filelogo!''}">
        		<input type="hidden" name="filelogourl" id="filelogourl" value="${microcaseData.filelogourl!''}" lay-verify="checkDesImg" >
				
				<div class="layui-form-item">
					<label for="L_title" class="layui-form-label">案例标题</label>
					<div class="layui-input-block">
						<input type="text" id="L_title" name="title" lay-verify="required|max81|checkContent" autocomplete="off" class="layui-input input-height-36" value="${microcaseData.title!''}">
					</div>
				</div>
				<div class="layui-form-item">
		            <label class="layui-form-label">描述图</label>
		            <div class="layui-input-block">
				      	<a class="layui-btn layui-btn-primary" id="desImgBtn"><i class="layui-icon">&#xe608;</i>上传图片</a>
				    </div>
		        </div>
		        <div class="layui-form-item  <#if microcaseData.filelogourl == "">layui-hide</#if>">
				    <label class="layui-form-label"></label>
				    <div class="layui-input-block">
				    	<img id="desImg" style="width:130px" <#if microcaseData.filelogourl != "">src="/${microcaseData.filelogourl!''}"</#if><#if microcaseData.filelogourl == "">src=""</#if>>
				    </div>
			    </div>
				<div class="layui-form-item">
					<label for="L_title" class="layui-form-label">案例类型</label>
					<div class="layui-input-block">
						<select name="charge" id="charge" required lay-verify="required" placeholder="请选择" lay-filter="selectCharge">
							<option value="">请选择</option>
							<option value="0" <#if microcaseData.charge == "0">selected</#if>>收费</option>
		                	<option value="1" <#if microcaseData.charge == "1">selected</#if>>免费</option>
						</select>
						<input type="text" name="price" id="price" autocomplete="off" class="layui-input price-num <#if microcaseData.charge == "1">price-none</#if>" placeholder="请输入案例价格" value="${microcaseData.price?string('0.00')}">
					</div>
				</div>
				<div class="layui-form-item">
					<label for="L_title" class="layui-form-label">案例等级</label>
					<div class="layui-input-block">
						<select name="gradedescribe" id="gradedescribe" placeholder="请选择案例等级" required lay-verify="required">
		                	<option value="">请选择案例等级</option>
							<#if dictgread?? && dictgread??>
							<#list dictgread as dic>
								<option value="${dic.id!''}" <#if microcaseData.gradedescribe == dic.id>selected</#if>>${dic.label!''}</option>
							</#list>
							</#if>
						</select>
					</div>
				</div>
				
				<div class="layui-form-item">
		            <label class="layui-form-label">发布时间</label>
		            <div class="layui-input-block">
		            	<input type="text" required lay-verify="required" class="layui-input price-num" id="time" value="${microcaseData.releasetime!?string("yyyy-MM-dd")}">
		            </div>
		        </div>
				<div class="layui-form-item">
					<label for="describecontent" class="layui-form-label" style="top: -2px;">请输入正文</label>
					<div class="layui-input-block">
						<textarea id="describecontent" name="describecontent" lay-verify="describecontent|checkContent|checkUeditorImg" placeholder="请输入内容" style="height: 194px;">${microcaseData.describecontent!''}</textarea>
					</div>
				</div>
				
				<div class="layui-form-item">
					<label for="parts" class="layui-form-label">使用的配件</label>
					<div class="layui-input-block">
						<#if dictList?? && dictList??>
						<#list dictList as parts>
							 <input type="checkbox" lay-verify="mountings" class="mountings ${parts.id!''}"  title="${parts.label!''}" value="${parts.id!''}" lay-skin="primary">
						</#list>
						</#if>
					</div>
				</div>
				
				<div class="layui-form-item">
					<div class="layui-input-block">
						<a class="button-upload" id="UploadButton">上传文件</a><label style="color:red;margin-left:10px">附件最多5个</label>
						<div class="upload-progress">
							
						</div>
						<input type="hidden" name="microcaseenclosureList" placeholder="附件列表" value="" lay-verify="<#if microcaseData.charge == '0'>microcaseenclosureList</#if>|checkImg">
					</div>
				</div>
				
				<div class="layui-form-item">
					<div class="layui-input-block">
						<input type="text" id="inputCode" required lay-verify="code" autocomplete="off" class="layui-input layui-input-code">
						<div class="code-show" id="checkCode" onclick="createCode()"> </div>
						<span class="code-show-push" onclick="createCode()">刷新</span>
					</div>
				</div>
				
				<div class="layui-form-item">
					<div class="layui-input-block">
						<a class="button-add" lay-filter="*" id="pay-btn" lay-submit="" data-pay="${fag}">编辑完成</a>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<script>
var dict= [];
var url = "/uploadmicrocasetwo",attachmentList = [],urlImg = "/uploadmicrocase";

<#list microanddictList as list>
	dict.push("${list.dictid!''}");
</#list>
<#list microenclosureList as list>
	attachmentList.push({"id":"${list.id!''}","enclosurename":"${list.enclosurename!''}","enclosureurl":"${list.enclosureurl!''}","filesize":"${list.filesize!''}","filetype":"${list.filetype!''}"});
</#list>
var filesLength = attachmentList.length;
$("#parts").val(dict.join());
$("#microcaseenclosureList").val(JSON.stringify(attachmentList));


layui.use(['laypage', 'layer', 'form', 'laydate'], function() {
	var form = layui.form();
	
    if(dict.length != 0 ){
    	$.each(dict,function(index,item){
        	$("."+item).attr("checked",true);
        });
    }
    
    $.each(attachmentList ,function(index,item){
		$(".upload-progress").append('<div id="progress'+item.id+'" class="upload-progress-li"><span title="'+item.enclosurename+'">'+item.enclosurename+'</span><div class="upload-progress-bar"><span class="color" style="width:100%;"></span></div><i class="layui-icon" onclick="deleteFiles(this,\''+item.id+'\',\'yes\')">&#x1006;</i></div>');
		$("#progress"+item.id + " .color").text("100%");
	})
    
	//根据选择显示
    form.on('select(selectCharge)', function(data){
    	if(data.value == 0){
    		$("input[name=price]").val("");
        	$("input[name=price]").css({"display":"inline-block"});
        	$("input[name=price]").attr("lay-verify","required|price");
        	
        	$("input[name=microcaseenclosureList]").attr("lay-verify","microcaseenclosureList");
    	}else{
    		$("input[name=price]").val(0);
        	$("input[name=price]").css({"display":"none"});
        	$("input[name=price]").attr("lay-verify","");
        	$("input[name=microcaseenclosureList]").attr("lay-verify","");
    		
    	}
     }); 
	
	var start = {
       istoday: true
       ,choose: function(dates){ //选择好日期的回调
     	  $("#releasetime").val(new Date(dates));
       }
    };
    
    $("#time").click(function(){
    	start.elem = this;
        laydate(start);
    });
    
    $("#releasetime").val( new Date($("#releasetime").val()));
    
    $(document).keyup(function(e) {
    	var theEvent = window.event || e;
    	var code = theEvent.keyCode || theEvent.which;
    	if (code == 13) {
    		$("#pay-btn").click();
    	}
    })
    
    form.verify({
    	checkUeditorImg: function(value, item){ 
	  	 var data = [], status={}, imgReg = /<img.*?(?:>|\/>)/gi;
		 //匹配src属性
		 var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
		 var arr = ue.getContent().match(imgReg);
		 if(arr){
			 for (var i = 0; i < arr.length; i++){
				 if(arr[i].match(srcReg)[1].indexOf("http://")<0){
					 data.push({
				        "dataId": i,
				        "url": "http://www.myboxlab.com"+arr[i].match(srcReg)[1],
				  		"time":new Date()
				      }); 
				 }

			 }
		 }
		 if(data.length>10){
			  return "最多上传10张图片！";
		 }else if(data.length>0){
			 var msg = msgSatatus(data);
		    if(msg!=""){
			  return msg;
		    }
		 }else{}
	  },
	  checkImg: function(value, item){ 
		  var data = [],status={};
		  if(attachmentList.length>0){
			 $.each(attachmentList,function(index,item){
				 var imgType = [".jpeg",".jpg","gif",".bmp",".png"];
				 var imgName = "."+item.enclosureurl.split(".")[1];
				 if(imgType.indexOf(imgName) >=0){
					 data.push({
				        "dataId": item.deleteId,
				        "url": "https://www.myboxlab.com/"+item.enclosureurl,
				  		"time":new Date()
				      }) 
				 }
			}) 
			var msg = msgSatatus(data);
			    if(msg!=""){
				  return msg;
			    } 
		  }
	  },
	  checkDesImg: function(value, item){ 
		  var data = [],status={};
		  if($("#filelogourl").val()!=""){
		  	data.push({
		        "dataId": $("#filelogo").val(),
		        "url": "https://www.myboxlab.com/"+$("#filelogourl").val(),
		  		"time":new Date()
		      }) 
			var msg = msgSatatus(data);
			    if(msg!=""){
				  return msg;
			    } 
		  }
	  },
    	checkContent: function(value, item){ 
			  var status = "";
			  if(item.name=="describecontent"){
				  value = ue.getContentTxt()
			  }
				$.ajax({
					  type:"POST",
					  url:"/checkConent",
					  data: {"content": value},
					  async: false,
					  success:function(data){
						 
						   var result = JSON.parse(data.requestmsg);
						   var resultsType = result.data[0].results[0].label;
						   if(result.data[0].results[0].suggestion!="pass"){
							   switch (resultsType)
								  {
								  case "spam":
									  status='您的内容包含垃圾信息';
								    break;
								  case "ad":
									  status='您的内容包含广告信息';
								    break;
								  case "politics":
									  status='您的内容包含渉政信息';
								    break;
								  case "terrorism":
									  status='您的内容包含暴恐信息';
								    break;
								  case "abuse":
									  status='您的内容包含辱骂信息';
								    break;
								  case "porn":
									  status='您的内容包含色情信息';
								    break;
								  case "flood":
									  status='您的内容包含灌水信息';
								    break;
								  case "contraband":
									  status='您的内容包含违禁信息';
								    break;
								  }
						   }
					  },
					  error:function(data){
						  console.log(data.requestmsg)
					  },
				  })
				  if(status!=""){
					  return status;
				  }
		  },
    	max81:function(value,item){
    		if(value.replace(/[^\u0000-\u00ff]/g,"***").length > 78){
    			return '标题过长！';
    		}
    	},
    	price: function(value, item){ 
    		if(value <= 0) {
   	  	       return '案例价格不能小于等于0';
   	  	     }else{
   	  	    	if(value === "" || value ==null){
   	  	    		return '请输入数字';
   	  	        }else if(isNaN(value)){
   		  	        return '请输入数字';
   		  	    }
   	  	    }
  	    },
  	  code: function(value, item){ 
  	    if(value.length <= 0) {
  	      return '请输入验证码';
  	     }
  	     else if(value.toUpperCase() != code.toUpperCase()) {
  	    	createCode();   
  	   		return '验证码输入有误！';
  	     }
  	     else {} 
  	  },
  	  describecontent: function(value, item){ 
  		value = ue.getContent()
      	if(value.length <= 0) {
  	      return '请输入正文';
  	     }
  	  },
  	 mountings: function(value, item){ 
  		var isEmptypartsVal = [];
	 	$('.mountings:checked').each(function() {
	 		isEmptypartsVal.push($(this).val());
	    });  
      	if(isEmptypartsVal.length <= 0) {
  	      return '请选择配件';
  	     }
	  },
  	  microcaseenclosureList: function(value, item){ 
      	if(isEmptyObject(attachmentList)) {
  	      return '请上传附件';
  	     }
	   }
  	}); 
    
	form.on('submit(*)', function(data){
    	
    	if($("#pay-btn").attr("data-pay") == "false" && $("#charge").val() == "0"){
    		
    		layer.open({
    			  icon: 2, 
    			  title:'提示',
    			  skin: 'layui-layer-demo', //样式类名
    			  closeBtn: 1, //不显示关闭按钮
    			  shadeClose: true, //开启遮罩关闭
    			  content: '请先添加个人收款信息',
    			  btn: ['确定'],
    			  yes: function(){
    				  window.location.href = "/user/payment.html";
    				  layer.closeAll();
    		      }
    			});
    	}else{
    		submit();
    	}
	});
	
	form.render(); //更新全部
   
});

/* 判断对象是否为空 */
function isEmptyObject(obj) {
	for (var key in obj) {
		return false;
	}
	return true;
}


var ue = UE.getEditor('describecontent',{
	//这里可以选择自己需要的工具按钮名称
	toolbars: [
		['Source','|', 'undo', 'redo', 'removeformat', 'backcolor', 'formatmatch','|', 'italic', 'underline', 'Bold', 'test',
			'forecolor','|', 'justifyleft', 'justifycenter', 'justifyright','|','insertorderedlist' ,'|',
			'fontfamily', 'fontsize','|',
			 'simpleupload','emotion'
		]
	],
	wordCount: false,					//开启字数统计
	elementPathEnabled : false
});

//上传初始化
var uploader = new plupload.Uploader({
	browse_button: 'UploadButton', //触发文件选择对话框的按钮，为那个元素id
	url: url, //服务器端的上传页面地址
	flash_swf_url: '${ctxStatic}/plupload/js//Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
	silverlight_xap_url: '${ctxStatic}/plupload/js/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
	filters : {
	 	max_file_size : '40mb',
	 	prevent_duplicates: "true" //不允许选取重复文件
	},
});

//在实例对象上调用init()方法进行初始化
uploader.init();
//绑定各种事件，并在事件监听函数中做你想做的事
uploader.bind('FilesAdded',function(uploader, files) {
	
	var number = 5-filesLength;
	if(uploader.files.length > number){ // 最多上传5个附件
        uploader.splice(number,999);
        layer.msg('最多上传5个附件！', {icon: 1})
    }
	$.each(files ,function(index,item){
		if($(".upload-progress .upload-progress-li").length <= 4){ 
			$(".upload-progress").append('<div id="progress'+item.id+'" class="upload-progress-li"><span title="'+item.name+'">'+item.name+'</span><div class="upload-progress-bar"><span class="color"></span></div></div>');
		}
	})
	uploader.start();
	
})

//上传后回调
uploader.bind('FileUploaded', function(uploader,UploadProgress, responseObject) {
	var obj = $.parseJSON(responseObject.response);
	$("#progress"+UploadProgress.id).append('<i id="'+UploadProgress.id+'" class="layui-icon" onclick="deleteFiles(this,\''+obj.fileId+'\')">&#x1006;</i>')
	var json = {};
	json.enclosurename = obj.fileName;
	json.enclosureurl = obj.filePath;
	json.id = obj.fileId;
	json.filetype = "";
	json.deleteId = UploadProgress.id;
	json.filesize = Math.ceil(UploadProgress.origSize / 1024);
	attachmentList.push(json);
});
uploader.bind('UploadProgress', function(up, file) {
  $("#progress"+file.id + " .color").css("width",file.percent + "%");
  if(file.percent == 100){
	  $("#progress"+file.id + " .color").text("100%");
  }
});
//报错
uploader.bind('Error',function(up,err) {
	 if(err.code == '-600'){
		 layer.msg('文件最多可上传40M', {icon: 5});
    }else if (err.code == '-602'){
     	  layer.msg('文件重复！', {icon: 5});
    }	
	 console.log(err)	
	
});
//上传描述图
//实例化一个plupload上传对象
var uploaderImg = new plupload.Uploader({
	browse_button:'desImgBtn', //触发文件选择对话框的按钮，为那个元素id
url: "${base}" + urlImg, //服务器端的上传页面地址
flash_swf_url: '${ctxStatic}/plupload/js//Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
silverlight_xap_url: '${ctxStatic}/plupload/js/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
filters: {
    mime_types: [{
            title: "Image files",
            extensions: "jpg,jpeg,png,gif"
        },

    ],
    max_file_size: '40mb',
},
});
//在实例对象上调用init()方法进行初始化
uploaderImg.init();
//绑定各种事件，并在事件监听函数中做你想做的事
uploaderImg.bind('FilesAdded',function(uploader,files){
	if(uploaderImg.settings.browse_button[0].id == "desImgBtn"){
		$("#desImg").parent().parent().removeClass("layui-hide");
		$("#desImg").attr("src","/images/loading-slide.gif");
	}
	uploaderImg.start()
});
//上传后回调
uploaderImg.bind('FileUploaded', function(uploader, UploadProgress, responseObject) {
	 var obj = $.parseJSON(responseObject.response);
	 if(uploader.settings.browse_button[0].id == "desImgBtn"){
		$("#desImg").attr("src","/" + obj.filePath );
		$("#filelogourl").val(obj.filePath);
		$("#filelogo").val(obj.fileName.split(".")[0]);
	}
});
//报错
uploaderImg.bind('Error', function(up, err) {
if (err.code == '-600') {
	layer.msg('文件最多可上传40M', {icon: 5});
}
});
function deleteFiles(i,fileId,old){
	var id = $(i).attr('id');
	if(id){
		uploader.removeFile(id);
	}
	$(i).parents(".upload-progress-li").remove();
	$.each(attachmentList, function(index,item){
		if(item.id == fileId){
			attachmentList.splice(index, 1);
			return false;
		}
	})
	if(old=="yes"){
		filesLength--;
	}
}

createCode();
function createCode() {
 code = "";
 var codeLength = 4; //验证码的长度
 var checkCode = document.getElementById("checkCode");
 var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
      'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
	  '1','2','3','4','5','6','7','8','9','0'); //所有候选组成验证码的字符，当然也可以用中文的
 for(var i = 0; i < codeLength; i++) {
  var charNum = Math.floor(Math.random() * 52);
  code += codeChars[charNum];
 }
 if(checkCode) {
  checkCode.className = "code-show";
  checkCode.innerHTML = code;
 }
}

function submit(){
	
	if($("#pay-btn").attr("disabled")){
		return false;
	}
	$("#pay-btn").attr("disabled",true);
	$("#pay-btn").html("正在提交...");
	
	var partsVal = [];
 	$('.mountings:checked').each(function() {
 		partsVal.push($(this).val());
    });  
 	$("#parts").val(partsVal.join());
    $("input[name=microcaseenclosureList]").val(JSON.stringify(attachmentList));
    
	$.ajax({
		type: "POST",
		url: "/microcase/update.html" ,
		dataType: "text",
		data: $("#myForm").serialize(),
		async: false,
		beforeSend:function(){
			
		},
		success: function(data) {
			
			if(data == "success"){
	       		 window.location.href = "/microcase/uploadcaseindex.html";
	       	 }else{
	       		 alert("失败！");
	       		 $("#pay-btn").attr("disabled",false);
	       		 $("#pay-btn").html("编辑完成");
	       	 }
		},
		error:function(data){
			alert("失败！");
      		$("#pay-btn").attr("disabled",false);
      		$("#pay-btn").html("编辑完成");
		}
		
	});
}

</script>